<template>
	<ul class="maputil">
		<li v-if="deConfig[0]"><Button type="primary" :class="{active:isShowJayou}" @click="changeShowJayou" title="加油站" long><img :src="gasIcon" /></long></Button></li>
		<li v-if="deConfig[1]"><Button type="primary" :class="{active:isShowStop}" @click="changeShowStop" title="停车场" long><i class="fa fa-product-hunt"></i></Button></li>
		<li v-if="deConfig[2]"><Button type="primary" :class="{active:isSatellite}" @click="changeSatellite" title="卫星图" long><i class="fa fa-globe"></i></Button></li>
		<li v-if="deConfig[3]"><Button type="primary" :class="{active:isTraffic}"  @click="changeTraffic" title="实时路况" long><i class="fa fa-road"></i></Button></li>
		<li v-if="deConfig[4]"><Button type="primary" :class="{active:isRanging}"  @click="changeRanging" title="测距" long><img :src="rulerIcon" style="margin-top: 4px;" /></Button></li>
		<li v-if="deConfig[5]"><Button type="primary" @click="changeZoom(zoom+1)" :disabled="zoom >= 16" long><i class="fa fa-plus"></i></Button></li>
		<li v-if="deConfig[6]"><Button type="primary" @click="changeZoom(zoom-1)" :disabled="zoom <= 5" long><i class="fa fa-minus"></i></Button></li>
	</ul>
</template>
<style lang="less">
	.maputil{
		li{margin-bottom: 3px;width: 35px;}
		button{height: 35px;padding:0;text-align: center;font-size: 16px;}
		button.active{background-color: darken(#02c2d7,15%);}
	}
</style>
<script>
	import rulerIcon        	 	 from '@/assets/images/ruler.png'
	import gasIcon               from '@/assets/images/gas.png'
	import MapPoint              from '@/plugin/Map/MapPoint'
	import gastation_little      from '@/assets/images/gastation_little.png'
	import parking_little        from '@/assets/images/parking_little.png'

	let map,mapCars={},mouseTool,satellite ,traffic,ranging,cars={},timer,pathtimer,mapLine,districtSearch,selectMapRail=[],mapStart;
	let danging,rangingEvent,cancelRaningEvent,placeSearch,jiayouGroup,stopGroup;


	export default {
		props:['map','config'],
		data(){
			return {
				rulerIcon,
				gasIcon,
				zoom:11,
				isRanging:false,
				isSatellite:false,
				isTraffic:false,
				isOpenJayou:false,
				isOpenStop:false,
				isShowStop:false,
				isShowJayou:false,
				mapBounds:null,
				// 测距相关数据
				rangingDatas:{
					//http://webapi.amap.com/theme/v1.3/markers/n/mark_b10.png
					points:[],
					pointsMarker:[]
				},
				satellite:null,
				traffic:null,
				placeSearch:null,
			}
		},
		watch:{
			map(){
				if(this.map === null) return;
				this.satellite = new AMap.TileLayer.Satellite({map:this.map,zIndex:0});
				this.satellite.hide();
				this.map.addControl(this.satellite);

				this.map.on("moveend",()=>{
					this.mapBounds = this.map.getBounds();
				})

				this.map.on('zoomend',e=>{
					this.zoom = this.map.getZoom();
					this.mapBounds = this.map.getBounds();
				})
				//事实交通图层
				this.traffic = new AMap.TileLayer.Traffic({map:this.map,zIndex:1});
				this.traffic.hide();
				this.map.addControl(this.traffic);

				this.placeSearch = new AMap.PlaceSearch({pageSize:50,children:0,autoFitView:false,showCover:false});

				// 驾车道路规划插件，用于测距
				this.danging = new AMap.Driving({map:this.map,hideMarkers:true});
			},
			mapBounds(v){
				if(this.isShowJayou){
					this.placeSearch.setType('加油站');
					this.placeSearch.searchInBounds("加油站",this.mapBounds, (status, result)=>{
				    if (status === 'complete' && result.info === 'OK') {
				    	if(jiayouGroup){
				    		jiayouGroup.forEach(a=>{
				    			a.obj.setMap(null);
				    			a.obj.clearOverlays();
				    		});
							}

							jiayouGroup = [];
				    	result.poiList.pois.forEach(a=>{
				    		jiayouGroup.push(new MapPoint({map:this.map,point:a.location,mkopts:{
				    			visible:this.isShowJayou,
				    			icon:new AMap.Icon({image:gastation_little,imageSize:new AMap.Size(19,19),size:new AMap.Size(19,19)}),
				       		offset: new AMap.Pixel(-19/2,-19/2)
				    		},
				    		data:{
				    			'名称':a.name,
				    			'地址':a.address
				    		},
					    	wdopts:{
				        	isOnly:true,
				        	width:220,
				        	labelWidth:'30%',
				        	isShow:false,
				        	zIndex:200,
				        }}));
				    	});
				    }
					});
				}
				if(this.isShowStop){
					this.placeSearch.setType('停车场');
					this.placeSearch.searchInBounds("停车场|车库",this.mapBounds, (status, result)=>{
				    if (status === 'complete' && result.info === 'OK') {
				    	if(stopGroup){
				    		stopGroup.forEach(a=>{
				    			a.obj.setMap(null);
				    			a.obj.clearOverlays();
				    		});
							}
							stopGroup = [];

				    	result.poiList.pois.forEach(a=>{
				    		stopGroup.push(new MapPoint({map:this.map,point:a.location,mkopts:{
				    			visible:this.isShowStop,
				    			icon:new AMap.Icon({image:parking_little,imageSize:new AMap.Size(19,19),size:new AMap.Size(19,19)}),
				       		offset: new AMap.Pixel(-19/2,-19/2)
				    		},
				    		data:{
				    			'名称':a.name,
				    			'地址':a.address
				    		},
					    	wdopts:{
				        	isOnly:true,
				        	width:220,
				        	labelWidth:'30%',
				        	isShow:false,
				        	zIndex:200,
				        }}));
				    	});
				    }
					});
				}
			},
			isShowJayou(v){
				if(v){
						jiayouGroup&&jiayouGroup.forEach(v=>v.marker.show());
				}else{
						jiayouGroup&&jiayouGroup.forEach(v=>v.obj.hide());
				}
			},
			isShowStop(v){
				if(v){
					stopGroup&&stopGroup.forEach(v=>v.marker.show());
				}else{
					stopGroup&&stopGroup.forEach(v=>v.obj.hide());
				}
			},
		},
		computed:{
			deConfig(){
				return this.config?this.config:[true,true,true,true,true,true,true];
			}
		},
		methods:{
			reset(){
				this.isOpenJayou&&this.changeShowJayou();
				this.isOpenStop&&this.changeShowStop();
				this.isSatellite&&this.changeSatellite();
				this.isTraffic&&this.changeTraffic();
				this.isRanging&&this.changeRanging();
			},
			changeShowJayou(){
				this.isOpenJayou = !this.isOpenJayou;
				this.isShowJayou = !this.isShowJayou;
				this.mapBounds = this.map.getBounds();
			},
			changeShowStop(){
				this.isOpenStop = !this.isOpenStop;
				this.isShowStop = !this.isShowStop;
				this.mapBounds = this.map.getBounds();
			},
			changeSatellite(){
				this.isSatellite?this.satellite.hide():this.satellite.show();
				this.isSatellite = !this.isSatellite;
			},
			changeTraffic(){
				this.isTraffic?this.traffic.hide():this.traffic.show();
				this.isTraffic = !this.isTraffic;
			},
			changeRanging(){
				//this.isRanging?ranging.turnOff(true):ranging.turnOn();
				this.isRanging = !this.isRanging;
				this.doRanging();
			},
			doRanging(){
				if (this.isRanging){
					this.danging.clear();// 先清空一次
					this.rangingDatas.cursor = this.map.getDefaultCursor();//保存地图默认鼠标
					this.map.setDefaultCursor("url('/static/img/ruler.cur'), default");
					this.map.on('click', this.rangingEvent);
					this.map.on('rightclick', this.cancelRaningEvent);
				} else {
					// 清除测距的覆盖物
					this.danging.clear();
					this.map.remove(this.rangingDatas.pointsMarker);
					// 移除事件
					this.map.off('click', this.rangingEvent);
					this.map.off('rightclick', this.cancelRaningEvent);
					// 恢复鼠标
					this.map.setDefaultCursor(this.rangingDatas.cursor);
					// 清空存储的数据
					this.rangingDatas.points = [];
					this.rangingDatas.pointsMarker = [];
				}
			},
			changeZoom(num){
				if(num<=16&&num>=5){
					this.zoom = num;
					this.map.setZoom(num);
				}
			},
			changeMouseTool(){
				this.openLeft = false;
				this.map.setDefaultCursor('crosshair');
				mouseTool.rectangle();
			},
			rangingEvent (e){
					// 最多设置pmax个点
					let pmax = 3;
					if (this.rangingDatas.points.length >= pmax){
						return this.$Modal.confirm({
							title: '测距',
							content: `最多设置${pmax}个测距点，是否清空数据重新测距？`,
							onOk: () => {
								// 清除测距的覆盖物
								this.danging.clear();
								this.map.remove(this.rangingDatas.pointsMarker);
								// 清空存储的数据
								this.rangingDatas.points = [];
								this.rangingDatas.pointsMarker = [];
							}
						});
					}
					let p = e.lnglat;// 点击的坐标
					this.rangingDatas.points.push(p);

					// 添加一个点
					let i = this.rangingDatas.points.length;
					let mk = new AMap.Marker({
						map:this.map,position:p,
						icon: new AMap.Icon({
								size: new AMap.Size(19, 31),//图标大小
								image: `http://webapi.amap.com/theme/v1.3/markers/n/mark_b${i}.png`
						})
					});
					this.rangingDatas.pointsMarker.push(mk);

					// 如果点大于等于2，就开始规划线路
					if (this.rangingDatas.points.length >= 2) {
						let sp = this.rangingDatas.points[0];
						let ep = this.rangingDatas.points[this.rangingDatas.points.length - 1];
						let jp = this.rangingDatas.points.filter((f,k) => {
							return k !== 0 && k !== this.rangingDatas.points.length - 1;
						});
						let	opts = {
							waypoints:[...jp]
						};
						this.danging.search(sp,ep,opts,(status,data) => {
							if (status === 'complete'){
								if (!data.routes[0]) return;
								let route = data.routes[0];
								let distance = (route.distance / 1000).toFixed(2);
								mk.setLabel({
									content:`${distance}KM`,
									offset: new AMap.Pixel(20, 0)
								});
							}
						});
					}
				},
				cancelRaningEvent(e){
					this.changeRanging();
				}
		}
	}
</script>
